const { app, BrowserWindow, ipcMain, dialog } = require('electron');
const { spawn } = require('child_process');
const fs = require('fs');
const path = require('path');

let mainWindow;
let ffmpegProcess = null;
let videoFiles = [];

function createWindow() {
    mainWindow = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
            nodeIntegration: true,
            contextIsolation: false, // Electron 12+ 默认 true，这里为了方便演示设置为 false
            enableRemoteModule: true, // 同样为了方便演示设置为 true，生产环境建议关闭
        },
    });

    mainWindow.loadFile('index.html');

    mainWindow.on('closed', () => {
        mainWindow = null;
        if (ffmpegProcess) {
            ffmpegProcess.kill();
        }
    });
}

app.on('ready', createWindow);

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        app.quit();
    }
});

app.on('activate', () => {
    if (mainWindow === null) {
        createWindow();
    }
});

ipcMain.on('select-files', async (event) => {
    const result = await dialog.showOpenDialog(mainWindow, {
        properties: ['openFile', 'multiSelections'],
        filters: [{ name: 'MP4 Files', extensions: ['mp4'] }],
    });

    if (!result.canceled && result.filePaths.length > 0) {
        videoFiles = result.filePaths;
        mainWindow.webContents.send('files-selected', videoFiles);
    }
});

ipcMain.on('start-stream', (event, rtmpUrl) => {
    if (!videoFiles || videoFiles.length === 0) {
        mainWindow.webContents.send('stream-status', '请先选择要推流的 MP4 文件。');
        return;
    }

    if (ffmpegProcess) {
        mainWindow.webContents.send('stream-status', '推流已在进行中，请先停止。');
        return;
    }

    // 创建 videos.txt 文件
    const content = videoFiles
        .map(filepath => `file '${filepath}'`)
        .join('\n');
    const videoListPath = path.join(app.getPath('temp'), 'videos.txt');
    fs.writeFileSync(videoListPath, content, 'utf8');

    const ffmpegArgs = [
        '-re',
        '-f', 'concat',
        '-safe', '0',
        '-i', videoListPath,
        '-vcodec', 'copy',
        '-acodec', 'copy',
        '-f', 'flv',
        rtmpUrl,
    ];

    ffmpegProcess = spawn('ffmpeg', ffmpegArgs);

    mainWindow.webContents.send('stream-status', `开始推流到: ${rtmpUrl}`);

    ffmpegProcess.stdout.on('data', (data) => {
        mainWindow.webContents.send('stream-log', data.toString());
    });

    ffmpegProcess.stderr.on('data', (data) => {
        mainWindow.webContents.send('stream-log', data.toString());
    });

    ffmpegProcess.on('close', (code) => {
        mainWindow.webContents.send('stream-status', `ffmpeg 进程已关闭，退出码 ${code}`);
        ffmpegProcess = null;
    });

    ffmpegProcess.on('error', (err) => {
        mainWindow.webContents.send('stream-status', `启动 ffmpeg 失败: ${err.message}`);
        ffmpegProcess = null;
    });
});

ipcMain.on('stop-stream', (event) => {
    if (ffmpegProcess) {
        ffmpegProcess.kill();
        mainWindow.webContents.send('stream-status', '已停止推流。');
        ffmpegProcess = null;
    } else {
        mainWindow.webContents.send('stream-status', '当前没有正在运行的推流。');
    }
});